import { Button, Input, PageHeader, Steps, Form, Select, message } from "antd";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import { EditorState, convertToRaw, ContentState } from "draft-js";
import { Editor } from "react-draft-wysiwyg";
import draftToHtml from "draftjs-to-html";
import htmlToDraft from "html-to-draftjs";
import { useState, useEffect } from "react";
import request from "../../api";
import globalStore from "../../store/globalStore";
import { useNavigate, useParams } from "react-router-dom";

const { reqCatrGread, reqPushNews, reqNewsDetial, reqChnageDrafts } = request;
const { Item } = Form;

const { Step } = Steps;

interface dataType {
  auditState: 0 | 1 | 2;
  author: string;
  categoryId: number;
  content: string;
  createTime: number;
  id: number;
  publishState: 0 | 1 | 2;
  publishTime: number;
  region: string;
  roleId: number;
  star: number;
  title: string;
  view: number;
}
interface fromData {
  title?: string;
  categoryId?: number;
  content?: string;
  region?: string;
  author?: string;
  roleId?: number;
  auditState?: number;
  publishState?: number;
  createTime?: number;
  star?: number;
  view?: number;
  id?: number;
  publishTime?: number;
}

interface slectType {
  id: number;
  title: string;
  value: string;
}
let fromData: fromData = {};
export default function index() {
  const { id } = useParams();
  const [fromChange] = Form.useForm();
  const nav = useNavigate();
  const [status, useStatus] = useState<0 | 1 | 2>(0);
  const [slected, useSlected] = useState<Array<slectType>>([]);
  const [textData, useTextData] = useState<EditorState>(
    EditorState.createEmpty()
  );

  const onFinish = (value: any) => {
    value.categoryId = Number(value.categoryId);
    Object.assign(fromData, value);
    useStatus(status ? 2 : 1);
  };
  const onEditorStateChange = (e: EditorState) => {
    useTextData(e);
    const result = draftToHtml(convertToRaw(textData.getCurrentContent()));
    if (result.trim() !== "<p></p>") {
      fromData.content = result;
    }
  };
  const getCateGreade = async () => {
    const result = (await reqCatrGread()) as unknown as Array<slectType>;
    useSlected(result);
  };
  const getNewsData = async () => {
    const result = (await reqNewsDetial(Number(id))) as unknown as dataType;
    fromChange.setFieldsValue(result);
    fromData = {
      ...result,
      auditState: 0,
    };
    const contentBlock = htmlToDraft(result.content);

    if (contentBlock) {
      const contentState = ContentState.createFromBlockArray(
        contentBlock.contentBlocks
      );
      const editorState = EditorState.createWithContent(contentState);
      useTextData(editorState);
    }
  };
  const getPushNews = async () => {
    if (id) {
      await reqChnageDrafts(Number(id), fromData);
      nav("/main/news-manage/draft");
    } else {
      await reqPushNews(fromData);
      message.success(
        fromData.auditState === 1
          ? "提交成功,请关注审核列表信息！"
          : "保存成功,请在草稿箱查看！"
      );
      fromData = {};
      fromChange.resetFields();
      useStatus(0);
    }
  };
  useEffect(() => {
    getCateGreade();
    if (!id) {
      globalStore.data.titel = "撰写新闻";
    } else {
      getNewsData();
    }
  }, []);
  return (
    <div style={{ width: "100%", height: "100%", backgroundColor: "white" }}>
      <PageHeader className="site-page-header" title="请在下方编辑新闻" />
      <Steps current={status} style={{ padding: "0 20px" }}>
        <Step title="基本信息" description="新闻标题，新闻分类" />
        <Step title="新闻内容" description="新闻主体内容" />
        <Step
          title="新闻提交"
          description={id ? "保存修改" : "保存草稿或者提交审核"}
        />
      </Steps>
      <div style={{ width: "100%", padding: "10% 10% 0", height: "80%" }}>
        <div
          style={{
            display: status === 1 ? "block" : "none",
            height: "80%",
            border: "1px solid black",
            marginBottom: "10px",
          }}
        >
          <Editor
            editorState={textData}
            wrapperClassName="demo-wrapper"
            editorClassName="demo-editor"
            onEditorStateChange={onEditorStateChange}
          />
        </div>

        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          form={fromChange}
          autoComplete="off"
          onFinish={onFinish}
          style={{
            display: status === 0 ? "block" : "none",
          }}
        >
          <Item
            label="标题"
            name="title"
            rules={[{ required: true, message: "标题是必填的" }]}
          >
            <Input />
          </Item>
          <Item
            label="类型"
            name="categoryId"
            rules={[{ required: true, message: "类型是必填的" }]}
          >
            <Select>
              {slected.map((item) => (
                <Select.Option value={item.id} key={item.id}>
                  {item.value}
                </Select.Option>
              ))}
            </Select>
          </Item>
          <Form.Item wrapperCol={{ offset: 10, span: 12 }}>
            <Button type="primary" htmlType="submit">
              下一步
            </Button>
          </Form.Item>
        </Form>
        {status > 0 && (
          <>
            <Button
              children="上一步"
              style={{ margin: "0 10px" }}
              onClick={() => {
                useStatus(status === 2 ? 1 : 0);
              }}
            />
            {status !== 2 && (
              <Button
                children="下一步"
                type="primary"
                onClick={() => {
                  const date = new Date();
                  if (!fromData.content) {
                    message.error("正文不允许为空");
                    return;
                  }
                  fromData.createTime = date.getTime();
                  fromData.publishTime = 0;
                  fromData.region =
                    localStorage.getItem("userRegion") || "全球";
                  fromData.star = 0;
                  fromData.view = 0;
                  fromData.author =
                    localStorage.getItem("userName") || "unknown";
                  fromData.roleId =
                    Number(localStorage.getItem("token")) || 999;
                  fromData.publishState = 0; //0未审核 1待发布 2已发布 3下线
                  fromData.auditState = 0; //0草稿 1待审核 2通过审核 3审核失败
                  useStatus(2);
                }}
              />
            )}
            {status === 2 &&
              (id ? (
                <>
                  <Button
                    children="保存修改"
                    type="ghost"
                    style={{ marginRight: "10px" }}
                    onClick={() => getPushNews()}
                  />
                </>
              ) : (
                <>
                  <Button
                    children="保存草稿"
                    type="ghost"
                    style={{ marginRight: "10px" }}
                    onClick={() => getPushNews()}
                  />
                  <Button
                    children="提交审核"
                    type="primary"
                    onClick={() => {
                      fromData.auditState = 1;
                      getPushNews();
                    }}
                  />
                </>
              ))}
          </>
        )}
      </div>
    </div>
  );
}
